/**
 * 退票时使用二分查找插入，此方法提交leetcode时，超时
 * @param {number} n
 */
export var SeatManager = function (n) {
  this.seats = new Array(n).fill(0).map((v, i) => i + 1)
  this.countUnreserve = 0
}

/**
 * @return {number}
 */
SeatManager.prototype.reserve = function () {
  if (this.countUnreserve) this.countUnreserve--
  return this.seats.shift()
}

/**
 * @param {number} seatNumber
 * @return {void}
 */
SeatManager.prototype.unreserve = function (seatNumber) {
  if (this.countUnreserve === 0 || this.seats.lenght === 0 || this.seats[0] > seatNumber) {
    this.countUnreserve++
    this.seats.unshift(seatNumber)
    return
  }
  let [l, r] = [0, this.countUnreserve ? this.countUnreserve - 1 : 0]
  let insertIdx = 0
  while (l <= r) {
    const mid = (r + l) >> 1
    if (this.seats[mid] <= seatNumber) {
      insertIdx = mid
      l = mid + 1
    } else {
      r = mid - 1
    }
  }
  this.seats.splice(insertIdx + 1, 0, seatNumber)
  console.log(this.seats)
  this.countUnreserve++
}

/**
 * Your SeatManager object will be instantiated and called as such:
 * var obj = new SeatManager(n)
 * var param_1 = obj.reserve()
 * obj.unreserve(seatNumber)
 */
